package com.tools.cleanmaster.ui.view.oversroll;

import android.view.MotionEvent;

/**
 * Created by apolunor on 15/12/10.
 */
public abstract class AbsOverScrollTool implements IOverScrollTool {

    public static final int DAMPING_COEFFICIENT = 2;
    //设置最大划出距离
    public static int MAX_DISTANCE = 300;
    //最小触发距离，防止抖动
    public static final int MIN_DISTANCE = 20;

    private int mLastDownY = 0;
    private int mDistance = 0;

    private boolean mCanPullDown = false;
    private boolean mCanPullUp = false;

    private boolean mForbidOverScrollTop = false;
    private boolean mForbidOverScrollBottom = false;

    @Override
    public boolean handleTouchEventDown(MotionEvent event) {
        mCanPullDown = isCanPullDown();
        mCanPullUp = isCanPullUp();
        mLastDownY = (int) event.getY();
        return false;
    }

    @Override
    public boolean handleTouchEventMove(MotionEvent event) {
        int delta = (int) (mLastDownY - event.getY());
        if ((!mForbidOverScrollTop && mCanPullDown && delta < 0)
                || (!mForbidOverScrollBottom && mCanPullUp && delta > 0)) {
            delta /= DAMPING_COEFFICIENT;
            if (Math.abs(delta) <= MAX_DISTANCE && Math.abs(delta) > MIN_DISTANCE) {
                scroll(delta);
                mDistance = delta;
            }
            return true;
        }
        mDistance = 0;
        return false;
    }

    @Override
    public boolean handleTouchEventUp(MotionEvent event) {
        return restoreIfNeed();
    }

    @Override
    public boolean handleTouchEventCancel(MotionEvent event) {
        return restoreIfNeed();
    }

    private boolean restoreIfNeed() {
        if (mDistance != 0) {
            rebound(mDistance);
            reset();
            return true;
        }
        return false;
    }

    protected void reset() {
        mLastDownY = 0;
        mDistance = 0;
        mCanPullDown = false;
        mCanPullUp = false;
    }

    protected boolean isCanPullDown() {
        return true;
    }

    protected boolean isCanPullUp() {
        return true;
    }

    public void setForbidOverScrollTop(boolean forbidOverScrollTop) {
        mForbidOverScrollTop = forbidOverScrollTop;
    }

    public void setForbidOverScrollBottom(boolean forbidOverScrollBottom) {
        mForbidOverScrollBottom = forbidOverScrollBottom;
    }
}
